import 'dart:async';
import 'dart:io';
import 'package:build/build.dart';
import 'package:dart_style/dart_style.dart';

/// A [PostProcessBuilder] which can be configured to consume any input
/// extensions and always deletes it primary input.
class CombineBuilder implements PostProcessBuilder {

  @override
  FutureOr<void> build(PostProcessBuildStep buildStep) async {
    print("CombineBuilder::::::::${buildStep.inputId.path}");

    String fileName = buildStep.inputId.path.replaceFirst('.sqlite.g.part', '.g.dart');
    File file2 = File(fileName);

    final buffer = StringBuffer();
    String content = await buildStep.readInputAsString();
    await buildStep.complete();
    buffer.write(content);

    Directory dir = Directory('.dart_tool/build/generated/${buildStep.inputId.package}/lib');
    List list = dir.listSync();
    for (var element in list) {
      if(element.path.endsWith(".dart.json")) {
        element as File;
        String content = await element.readAsString();
        buffer.write(content);
        element.deleteSync();
      }
    }
    String s = DartFormatter(fixes: [StyleFix.singleCascadeStatements]).format(buffer.toString());
    await file2.writeAsString(s);
    return null;
  }

  @override
  Iterable<String> get inputExtensions => ['.g.part'];
}
